<?php

namespace App\Http\Controllers\Api;

use App\Model\AdminTable;
use App\Model\ClassTable;
use App\Model\CommentTable;
use App\Model\CouponListTable;
use App\Model\FieldTable;
use App\Model\InviteTeamTable;
use App\Model\LockSetTable;
use App\Model\OrderTable;
use App\Model\PriceSetTable;
use App\Model\PriceSetTempTable;
use App\Model\StorefrontTable;
use App\Model\TeamTable;
use App\Model\TimeBlockTable;
use App\Model\UserLevelSetTable;
use App\Model\UserTable;
use App\Repository\BaseController\ApiController;
use App\Repository\Common\ConstTable;
use App\Repository\Common\Fun;
use App\Repository\Lib\Weixin;
use App\Repository\Sys\JsonRespose;
use App\Repository\Sys\Str;
use App\Repository\Sys\Sys;
use EasyWeChat\Foundation\Application;
use Illuminate\Support\Facades\Log;


class OrderController extends ApiController
{
    /**
     * @api {get} /api/order/discount 获取优惠券和折扣信息
     * @apiGroup Api-Order
     * @apiDescription  说明: 无
     *
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": 1,
     * "msg": "操作成功!",
     * "data": {
     * "vip": "",
     * "discount": "",
     * "coupon_list": [
     * {
     * "id": "2",
     * "money": "1.00",
     * "name": "1",
     * "uid": "1",
     * "start_time": "1",
     * "end_time": "1",
     * "dateline": "1517988477",
     * "number": "0",
     * "coupon_id": "",
     * "status": 0  #1 可以使用   0不能使用
     * },
     * {
     * "id": "3",
     * "money": "1.00",
     * "name": "1",
     * "uid": "1",
     * "start_time": "1",
     * "end_time": "1",
     * "dateline": "1517989316",
     * "number": "1",
     * "coupon_id": "1",
     * "status": 0
     * }
     * ]
     * }
     * }
     *
     */
    public function getDiscount()
    {
        $uid = Sys::getUid();
        if (!$uid) {
            return Sys::getUidFail();
        }

        $price = \Request::get('price');

        if(!$price){
            return JsonRespose::fail('缺少price');
        }

        $user_data = UserTable::ORM()->where('id', $uid)->first();

        $level_data = UserLevelSetTable::ORM()->where('id', $user_data->vip_level_id)->first();

        $coupon_res = CouponListTable::ORM()->where('uid', $uid)->where('use_status', 1)->get();

        $coupon_list = [];
        foreach ($coupon_res as $v) {
            if ($v->start_time > time() or $v->end_time < time() or $price < $v->money) {
                $status = 'disabled'; //不可使用 0
            } else {
                $status = '';
            }
            $v->status = $status;
            unset($v->use_status);
            $coupon_list[] = $v;
        }
        return JsonRespose::success([
            'vip' => $level_data->level_name,
            'discount' => $level_data->discount, //折扣
            'coupon_list' => $coupon_list
        ]);
    }

    //  所有的东西支付成功后才使用 或者更新  不做取消订单操作   1.积分等级  2.优惠券
    /**
     * @api {post} /api/order/create-order 创建订单调起支付接口
     * @apiGroup Api-Order
     * @apiDescription  说明: 无
     *
     * @apiParam {Int} field_id  球场id
     * @apiParam {Int} day  日期如2018-01-01
     * @apiParam {Int} start_time  开始时间如9:00
     * @apiParam {Int} end_time  结束时间
     * @apiParam {Int} coupon_id  优惠券id
     * @apiParam {Int} order_type  订单类型 1约战 2应战  3普通订场
     * @apiParam {Int} invite_id  约战不用传,应战需要传
     * @apiParam {Int} team_id  应战约战id,type不为3时必填
     * @apiParam {Int} join_num  人数,type不为3时必填
     * @apiParam {Int} avg_age  平均年龄,type不为3时必填
     * @apiParam {Int} colour  颜色,type不为3时必填
     * @apiParam {Int} desc  要求,type不为3时必填
     *
     *
     *
     * @apiSuccessExample {json} Success-Response:
     *
     *{
     * "code": 1,
     * "msg": "操作成功!",
     * "data": {
     * "order_id": 7,
     * "wx_pay_config": {
     * "appId": "wxe222b512aca754b8",
     * "nonceStr": "5a8d203f847b7",
     * "package": "prepay_id=wx20180221153111634c66ddab0946896813",
     * "signType": "MD5",
     * "paySign": "E2E66EDEE553FCBD64C2CA5BE929C67B",
     * "timestamp": 1519198271
     * }
     * }
     * }
     */
    public function postCreateOrder()
    {
        $uid = Sys::getUid();
        if (!$uid) {
            return Sys::getUidFail();
        }


        $field_id = \Request::get('field_id');
        $field_type = \Request::get('type');//场地类型
        $day = \Request::get('day');
        $start_time = \Request::get('start_time');  //字符串
        $end_time = \Request::get('end_time');
        $coupon_id = \Request::get('coupon_id', 0);

        $order_type = \Request::get('order_type', 3);  //订单类型 1约战 2应战  3普通订场
        $invite_id = \Request::get('invite_id', 0);  //应 id

        $team_id = \Request::get('team_id', 0);  //不为3时下列必填
        $join_num = \Request::get('people_number');//人数
        $avg_age = \Request::get('avg_age');
        $colour = \Request::get('colour');
        $desc = \Request::get('desc');


        if (!$field_id or !$day or !$start_time or !$end_time or !$order_type) {
            return JsonRespose::fail();
        }

        $day = Str::getDayTime($day);
        if ($day < Str::getDayTime()) {
            return JsonRespose::fail('时间错误');

        }

        if($invite_id){
            $res = InviteTeamTable::ORM()->where('id', $invite_id)->first();
            $day=$res->game_day;

        }
        $field__status = TimeBlockTable::getBlockStatus($day, $field_id, Str::timeTotime($start_time), Str::timeTotime($end_time));
        $field__info = FieldTable::getFieldInfo($field_id);
        $user_data = UserTable::ORM()->where('id', $uid)->first();


        if ($user_data->status != 1) {
            return JsonRespose::fail('用户已禁用');
        }


        $level_data = UserLevelSetTable::ORM()->where('id', $user_data->vip_level_id)->first();

        $openid = $user_data->open_id; // get openid

        if ($field__status['lock'] > 0 or $field__status['order_id'] > 0) {
            return JsonRespose::fail('场地已被锁定或约定');
        }

        $money = $field__status['price'];


        /*1. bcadd 任意精度数的相加
                  2. bcsub 任意精度数的减法
                  3. bcmul 乘法， bcdiv除法 */


        if ($order_type == 3) {
            $object_id = 0;
            $order_status = 2;
        } else {
            $object_id = $invite_id;
            $tmp_money=0;
            $money =$tmp_money= bcdiv($money, 2, 2);   //价格计算不一样

            $order_status = 1;
        }

        //折扣
        if ($level_data) {
            $money = bcmul($money, ($level_data->discount / 10), 2);
        }

        if ($coupon_id) {
            $coupon_res = CouponListTable::ORM()->where('id', $coupon_id)->first();
            //判断是否过期2
            if ($coupon_res->use_status == 2) {
                return JsonRespose::fail('优惠券已使用');
            }
            if ($coupon_res->start_time > time() or $coupon_res->end_time < time()) {
                return JsonRespose::fail('无法使用的优惠券,请确认优惠券的有效时间');
            }
            $money = bcsub($money, $coupon_res->money, 2);

        }

        if ($money == 0) {
            return JsonRespose::fail('优惠后价格小于0.01，无法使用微信支付');
        }

        if ($order_type == 1) {

            $team_res = TeamTable::ORM()->where('id', $team_id)->first();
            if ($team_res->status == 2) {
                return JsonRespose::fail('球队已禁用');
            }


            $s = InviteTeamTable::ORM()->insertGetId([
                'create_uid' => $uid,
                'team_id' => $team_id,
                'join_team_id' => 0,
                'join_num' => $join_num,
                'avg_age' => $avg_age,
                'colour' => $colour,
                'desc' => $desc,
                'start_time' => Str::timeTotime($start_time, false),  //从1970开始
                'end_time' => Str::timeTotime($end_time, false),
                'field_id' => $field_id,
                'type' => $field_type,
                'money' => $tmp_money,
                'game_day' => $day,
                'status' => 1,
                'dateline' => time(),
            ]);
            $object_id = $s;
            if (!$s) {
                return JsonRespose::fail('插入战队表信息失败1');
            }
        }
        if ($order_type == 2) {

            $team_res = TeamTable::ORM()->where('id', $team_id)->first();
            if ($team_res->status == 2) {
                return JsonRespose::fail('球队已禁用');
            }


            $s = InviteTeamTable::ORM()->where('id', $invite_id)->update([
                'join_team_id' => $team_id,
                'slave_join_num' => $join_num,
                'slave_avg_age' => $avg_age,
                'slave_colour' => $colour,
                'slave_desc' => $desc,
            ]);
            if (!$s) {
                Log::error("插入战队表信息失败2");
//                return JsonRespose::fail('插入战队表信息失败2');
            }
        }
        // 获取微信  支付参数
        $order_data = [
            'order_type' => $order_type,
            'object_id' => $object_id,
            'money' => $money, //  现价
            'uid' => $uid,
            'weixin_sn' => '',
            'field_id' => $field_id,
            'start_time' => Str::timeTotime($start_time),
            'end_time' => Str::timeTotime($end_time),
            'day_time' => $day,
            'coupon_id' => $coupon_id,
            'dateline' => time(),
            'status' => $order_status,
            'pay_type' => 1,
            'is_comment' => 2,
            'storefront_id' => $field__info['storefront_id'],
            'field_price' => $field__status['price'],
        ];

        $order_id = OrderTable::ORM()->insertGetId($order_data);

        $wx_pay_config = Weixin::getWxPayConfig($order_type, $money, $order_id, $openid);

        if ($wx_pay_config == false) {
            return JsonRespose::fail('请求微信支付失败,请稍后重试');
        }
        return JsonRespose::success([
            'order_id' => $order_id,
            'wx_pay_config' => $wx_pay_config
        ]);
    }


    /**
     * @api {get} /api/order/order-list 订单列表
     * @apiGroup Api-Order
     * @apiDescription  说明: 无
     *
     * @apiParam {Int} page  -
     * @apiParam {Int} page_num  -
     * @apiParam {Int} type  0全部 1 已订场  2已匹配  3 已完成 4待评价
     * @apiParam {Int} team_id  团队id,查看某个团队的对战记录
     *
     * @apiSuccess {String} status 状态,6个,1已订场 2以匹配 3已完成 4待评价 5已取消 6未匹配
     *
     * @apiSuccessExample {json} Success-Response:
     *
     *
     * {
     * "code": 1,
     * "msg": "操作成功!",
     * "data": {
     * "count": "6",
     * "list": [
     * {
     * "order_id": "6",
     * "status": 1,
     * "img": "xxxx",
     * "time": "1970-01-01  11:00-13:00 周四",
     * "address": {
     * "storefront_name": "武昌",
     * "type_text": "5V5",
     * "field_id": "1",
     * "field_type": "5",
     * "storefront_id": "1",
     * "number": "1"
     * },
     * "phone": 15999999999,
     * "dateline": "2018-02-13",
     * "team_info": []
     * },
     * {
     * "order_id": "5",
     * "status": 1,
     * "img": "xxxx",
     * "time": "1970-01-01  11:00-13:00 周四",
     * "address": {
     * "storefront_name": "武昌",
     * "type_text": "5V5",
     * "field_id": "1",
     * "field_type": "5",
     * "storefront_id": "1",
     * "number": "1"
     * },
     * "phone": 15999999999,
     * "dateline": "2018-02-13",
     * "team_info": []
     * },
     * {
     * "order_id": "4",
     * "status": 1,
     * "img": "xxxx",
     * "time": "1970-01-01  11:00-13:00 周四",
     * "address": {
     * "storefront_name": "武昌",
     * "type_text": "5V5",
     * "field_id": "1",
     * "field_type": "5",
     * "storefront_id": "1",
     * "number": "1"
     * },
     * "phone": 15999999999,
     * "dateline": "2018-02-13",
     * "team_info": []
     * },
     * {
     * "order_id": "3",
     * "status": 1,
     * "img": "xxxx",
     * "time": "1970-01-01  11:00-13:00 周四",
     * "address": {
     * "storefront_name": "武昌",
     * "type_text": "5V5",
     * "field_id": "1",
     * "field_type": "5",
     * "storefront_id": "1",
     * "number": "1"
     * },
     * "phone": 15999999999,
     * "dateline": "2018-02-13",
     * "team_info": []
     * },
     * {
     * "order_id": "2",
     * "status": 1,
     * "img": "xxxx",
     * "time": "1970-01-01  11:00-13:00 周四",
     * "address": {
     * "storefront_name": "武昌",
     * "type_text": "5V5",
     * "field_id": "1",
     * "field_type": "5",
     * "storefront_id": "1",
     * "number": "1"
     * },
     * "phone": 15999999999,
     * "dateline": "2018-02-13",
     * "team_info": []
     * },
     * {
     * "order_id": "1",
     * "status": 6,
     * "img": "xxxx",
     * "time": "1970-01-01  08:00-08:00 周四",
     * "address": {
     * "storefront_name": "武昌",
     * "type_text": "5V5",
     * "field_id": "1",
     * "field_type": "5",
     * "storefront_id": "1",
     * "number": "1"
     * },
     * "phone": 15999999999,
     * "dateline": "1970-01-01",
     * "team_info": {
     * "master": {
     * "id": "1",
     * "name": "1",
     * "img": "1",
     * "create_time": "1970-01-01",
     * "colour": "1",
     * "desc": "",
     * "admin_id": "1",
     * "avg_age": "",
     * "people_number": "1",
     * "status": "1"
     * },
     * "slave": {
     * "id": "1",
     * "name": "1",
     * "img": "1",
     * "create_time": "1970-01-01",
     * "colour": "1",
     * "desc": "",
     * "admin_id": "1",
     * "avg_age": "",
     * "people_number": "1",
     * "status": "1"
     * }
     * }
     * }
     * ],
     * "page": 1
     * }
     * }
     *
     */
    public function getOrderList()
    {
        $uid = Sys::getUid();
        if (!$uid) {
            return Sys::getUidFail();
        }
        $page = \Request::get('page', 1);
        $limit = \Request::get('page_num', 10);
        $type = \Request::get('type', 0);  //0全部 1 已订场  2已匹配  3 已完成 4待评价 5(1 or 2)

        $team_id = \Request::get('team_id');   //团队id


        $where = 'pay_type>=2';
        $param = [];


        //对列表进行筛选 4个
        if ($type == 0) {
            $where .= " and uid={$uid}";
        }
        if ($type == 1) { //

            $time = strtotime(date('Y-m-d'));
            $time2 = strtotime('1970-01-01 ' . date('H:i:s'));



            $where .= " and order_type= 3 and pay_type = 2 and order.status = 2   and order.day_time>= {$time}  and  order.end_time > {$time2}  ";
            $where .= " and uid={$uid}";

        }
        if ($type == 2) { //  已匹配
            $where .= ' and (order_type=1 or order_type=2) and pay_type = 2 and order.status = 2';
            $where .= " and uid={$uid}";
            //  $where .= " and (team_id={$uid} or join_team_id={$uid})";
        }
        if ($type == 3) { // 已完成
            $time = time();
            $time2 = strtotime('1970-01-01 ' . date('H:i:s'));

            $where .= " and pay_type = 2  and order.status = 2 and order.day_time< {$time}  and  order.end_time < {$time2}";
            $where .= " and uid={$uid}";
        }
        if ($type == 4) { // 待评价
            $time = time();
            $time2 = strtotime('1970-01-01 ' . date('H:i:s'));

            $where .= " and (order_type=1 or order_type=2) and order.status = 2 and is_comment=2  and order.day_time< {$time}  and  order.end_time < {$time2} ";
            $where .= " and uid={$uid}";
        }
        if ($type == 5) { // 1 or 2
            $where .= ' and ((order_type= 3 and pay_type = 2 and order.status = 2)  or ((order_type=1 or order_type=2) and pay_type = 2 and order.status = 2)) and order_type!=3';
            $where .= " and uid={$uid}";
        }
        if ($team_id) {
            $where .= " and order_type !=3 and (invite_team.team_id={$team_id} or invite_team.join_team_id={$team_id})";
        }
//          $where .=" and order_id=818"; // test


        $count = \DB::select("select count(*) as c  from `order`  LEFT JOIN invite_team ON invite_team.id=`order`.object_id WHERE {$where}", $param)[0]->c;
        $param['offset'] = ($page - 1) * $limit;
        $param['limit'] = $limit;
        $res = \DB::select("select `order`.* from `order` LEFT JOIN invite_team ON invite_team.id=`order`.object_id WHERE {$where} ORDER BY order_id DESC limit :offset,:limit", $param);
        $data = [];


        foreach ($res as $v) {

//            var_dump($time,$time2,$v);die;
            //对描述进行翻译 6个 1已订场 2以匹配 3已完成 4待评价 5已取消 6未匹配

            $team_info = [];  ////['master' => ['name' => 'xx', 'img' => 'xxx', 'colour' => ''], 'slave' => ['name' => 'xx', 'img' => 'xxx', 'colour' => '']];

            if ($v->order_type != 3) {
                $team_info = OrderTable::team_info($v->object_id, $v->order_id);
            }
            $field_res=FieldTable::getFieldInfo($v->field_id);

            $data[] = [
                'order_id' => $v->order_id,
                'status' => OrderTable::status($type, $v->order_type, $v->pay_type, $v->is_comment, $v->status, strtotime(date('Y-m-d ', $v->day_time) . date('H:i:s', $v->end_time))),  // 翻译状态
                'img' => '/img/default_160_160.png',  //  订单列表没有图片
                'time' => date('Y-m-d ', $v->day_time) . ' ' . date('H:i', $v->start_time) . '-' . date('H:i', $v->end_time) . ' 周' . Str::getWeek($v->day_time),
                'address' => $field_res,
                'phone' => $field_res['phone'],
                'dateline' => date('Y-m-d', $v->dateline),
                'team_info' => $team_info,//
                'money' => $v->money,
                'order_type'=>$v->order_type,
                'day' => date('m/d', $v->day_time),
                'team_time' => date('H:i', $v->start_time) . '-' . date('H:i', $v->end_time). ' 周' . Str::getWeek($v->day_time),
            ];
        }
        return JsonRespose::success([
            'count' => $count,
            'list' => $data,
            'page' => $page,
        ]);
    }


    /**
     * @api {get} /api/order/order-info 订单详情
     * @apiGroup Api-Order
     * @apiDescription  说明: 无
     *
     * @apiParam {Int} order_id  -
     *
     *
     * @apiSuccessExample {json} Success-Response:
     *
     *
     * {
     * "code": 1,
     * "msg": "操作成功!",
     * "data": {
     * "order_id": "1",
     * "status": 6,
     * "time": "01/01  08:00-08:00",
     * "address": {
     * "storefront_name": "武汉-武昌",
     * "type_text": "5V5",
     * "field_id": "1",
     * "field_type": "5",
     * "storefront_id": "1",
     * "number": "1"
     * },
     * "phone": 15999999999,
     * "dateline": "1970-01-01",
     * "team_info": {
     * "master": {
     * "img": "1",
     * "name": "1",
     * "join_num": "1",
     * "avg_age": "1",
     * "colour": "1",
     * "desc": "1",
     * "comment": [
     * {
     * "content": "123",
     * "content_num": "11"
     * }
     * ]
     * },
     * "slave": {
     * "img": "1",
     * "name": "1",
     * "join_num": "",
     * "avg_age": "",
     * "colour": "",
     * "desc": "",
     * "comment": [
     * {
     * "content": "123",
     * "content_num": "11"
     * }
     * ]
     * }
     * },
     * "money": "1.00",
     * "comment": []
     * }
     * }
     *
     */
    public function getOrderInfo()
    {
        $uid = Sys::getUid();
        if (!$uid) {
            return Sys::getUidFail();
        }
        $order_id = \Request::get('order_id');
        if (!$order_id) {
            return JsonRespose::fail();
        }
        $order_info = OrderTable::ORM()->where('order_id', $order_id)->first();
        $team_info = [];

        if ($order_info->order_type != 3) {
            $team_info = OrderTable::team_info($order_info->object_id, $order_id);
        }

        //  可能是订场服务的评论
        $com = [];
        if ($order_info->order_type == 3) {
            $comment = CommentTable::ORM()->where('order_id', $order_id)->limit(9)->get();
            foreach ($comment as $v) {
                $com[] = [
                    'content' => $v->content,
                    'content_num' => $v->content_num
                ];
            }
        }

        $field_res=FieldTable::getFieldInfo($order_info->field_id);
        $data = [
            'order_id' => $order_info->order_id,
            'status' => OrderTable::status($order_info->order_type, $order_info->pay_type, $order_info->is_comment, $order_info->status, strtotime(date('Y-m-d ', $order_info->day_time) . date('H:i:s', $order_info->end_time))),  // 翻译状态
            'time' => date('m/d ', $order_info->day_time) . ' ' . date('H:i', $order_info->start_time) . '-' . date('H:i', $order_info->end_time).' 周'.Str::getWeek($order_info->day_time),
            'address' => FieldTable::getFieldInfo($order_info->field_id),
            'phone' => $field_res['phone'],
            'dateline' => date('Y-m-d', $order_info->dateline),
            'team_info' => $team_info,//
            'money' => $order_info->money,
            'comment' => $com,
        ];

        return JsonRespose::success($data);

    }

    /**
     * @api {post} /api/order/cancel  取消订单-退款
     * @apiGroup Wap-Order
     * @apiDescription  说明: 只有主队72小时前可以取消
     *
     * @apiParam {Int} order_id 订单
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     * "code": 1,
     * "msg": "操作成功!",
     * "data": ''
     *
     * }
     */
    public function postCancel()
    {
        // 取消订单 测试 ing
        $order_id = \Request::get('order_id');

        $order = OrderTable::ORM()->where('order_id', $order_id)->first();

        $t = strtotime(date('Y-m-d ', $order->day_time) . date('H:i:s', $order->end_time));

        //72 小时判断

        if ($order->order_type == 3) {
            if (( $t- time()) <= 259200) {
                return JsonRespose::fail("72小时内无法取消订单");
            }
        }


        if (!$order_id) {
            return JsonRespose::fail();
        }
        $res = OrderTable::orderBack($order_id);

        return JsonRespose::done($res);
    }
}